package com.kaka.bus.engine.user.login;

import android.content.Intent;
import android.os.Build;
import android.support.v7.widget.AppCompatButton;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jakewharton.rxbinding.view.RxView;
import com.kaka.bus.AppCenter;
import com.kaka.bus.R;
import com.kaka.bus.base.BaseActivity;
import com.kaka.bus.bean.HttpWrapper;
import com.kaka.bus.bean.LoginBean;
import com.kaka.bus.bean.UserInfo;
import com.kaka.bus.constant.Constant;
import com.kaka.bus.engine.HomeActivity;
import com.kaka.bus.engine.user.forget.ForgetActivity;
import com.kaka.bus.engine.user.register.RegistActivity;
import com.kaka.bus.engine.user.register.RegistPwdActivity;
import com.kaka.bus.util.U;
import com.kaka.bus.util.WindowSoftModeAdjustResizeExecutor;
import com.kaka.bus.util.logger.Logger;
import com.kaka.bus.view.LoginView;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;

/**
 * Created by zhangqi on 2016/9/28.
 * e-mail : ${email}
 * desc :
 */

public class LoginActivity extends BaseActivity<LoginPresenter> implements LoginContract.View {

    @BindView(R.id.toolbar_back)
    ImageView mToolbarBack;
    @BindView(R.id.toolbar_name)
    TextView mToolbarName;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.edt_login_username)
    EditText mEdtLoginUsername;
    @BindView(R.id.edt_login_password)
    EditText mEdtLoginPassword;
    @BindView(R.id.btn_login)
    AppCompatButton mBtnLogin;
    @BindView(R.id.btn_login_register)
    TextView mBtnLoginRegister;
    @BindView(R.id.btn_login_forget)
    TextView mBtnLoginForget;
    @BindView(R.id.login_rb_sms)
    RadioButton mLoginRbSms;
    @BindView(R.id.login_rb_pwd)
    RadioButton mLoginRbPwd;
    @BindView(R.id.login_rg)
    LoginView mLoginRg;
    @BindView(R.id.login_phone)
    EditText mLoginPhone;
    @BindView(R.id.login_send)
    TextView mLoginSend;
    @BindView(R.id.login_rl_send)
    RelativeLayout mLoginRlSend;

    private String phone;
    private String pwd;

    /**
     * 短信还是密码登录
     */
    private final int SMS = 1;
    private final int PWD = 2;
    private int mIsSms = SMS;
    private String mSmsPhone;
    private String mSmsCode;
    private String mModel;

    @Override
    protected void initView() {
        super.initView();
        WindowSoftModeAdjustResizeExecutor.assistActivity(this);
        mToolbarName.setText("登录");
        mToolbarBack.setOnClickListener(v -> finish());
        mLoginRg.check(R.id.login_rb_sms);
        mModel = U.getModel();

        Intent intents = getIntent();
        if (intents != null && intents.getAction() != null && intents.getAction().equals(RegistPwdActivity.TAG_TOLOGIN_REQUEST)) {
            String phone = intents.getStringExtra(RegistPwdActivity.PHONE);
            String pwd = intents.getStringExtra(RegistPwdActivity.PWD);
            mPresenter.login(phone, pwd, AppCenter.getTokenKey(), Build.VERSION.RELEASE, mModel);
        }
    }

    @Override
    protected void initListener() {
        RxView.clicks(mBtnLogin)
                .throttleFirst(3, TimeUnit.SECONDS)
                .subscribe(v -> login());

        mBtnLoginRegister.setOnClickListener(v -> {
            startActivity(new Intent(this, RegistActivity.class));
        });

        mBtnLoginForget.setOnClickListener(v -> {
            startActivity(new Intent(this, ForgetActivity.class));
        });

        mLoginRg.setOnCheckListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.login_rb_sms:
                    mIsSms = SMS;
                    mEdtLoginPassword.setVisibility(View.GONE);
                    mLoginRlSend.setVisibility(View.VISIBLE);
                    mEdtLoginPassword.setText("");
                    break;
                case R.id.login_rb_pwd:
                    mIsSms = PWD;
                    mEdtLoginPassword.setVisibility(View.VISIBLE);
                    mLoginRlSend.setVisibility(View.GONE);
                    mLoginPhone.setText("");
                    break;
            }
            mEdtLoginUsername.setText("");
            mLoginRg.check(checkedId);
        });

        mLoginSend.setOnClickListener(v -> {
            String phone = getText(mEdtLoginUsername);
            if (!U.isMobileExact(phone)) {
                showMessage(R.string.enterOkPhone);
                return;
            }
            mSmsPhone = phone;
            mPresenter.sendSms(phone, AppCenter.getTokenKey(), "login", Constant.PLATFORM);

        });
    }

    private void login() {
        Logger.i("用户开始登录");
        phone = mEdtLoginUsername.getText().toString();
        pwd = mEdtLoginPassword.getText().toString();
        String sms = mLoginPhone.getText().toString();
        if (!U.isMobileExact(phone)) {
            showMessage(R.string.enterOkPhone);
            return;
        }

        if (mIsSms == SMS) {
            if (!phone.equals(mSmsPhone)) {
                showMessage("请输入发送验证码的手机号码!");
                return;
            }

            mPresenter.loginOnSms(phone, sms, AppCenter.getTokenKey(), Constant.PLATFORM, Build.VERSION.RELEASE, mModel);
        } else {
            mPresenter.isExist(phone);
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }

    @Override
    public void loginSuccess(HttpWrapper<LoginBean> data) {
        if (Constant.SUCCESS_CODE.equals(data.code)) {
            LoginBean person = data.getData();
            showMessage(data.info);

            UserInfo userInfo = new UserInfo();
            userInfo.setPhone(phone);
            userInfo.setPassword(pwd);
            userInfo.setTokenId(person.getToken());
            userInfo.setId(person.getPer_id());

            setUserInfo(userInfo);
            startActivity(new Intent(this, HomeActivity.class));
            finish();
        } else if (Constant.ERROR_CODE.equals(data.code)) {
            showMessage(data.info);
        } else if (Constant.BQSLOSE_CODE.equals(data.code)) {
            showMessage("非法登录");
        } else {
            showMessage(data.info);
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public void phoneState(HttpWrapper<String> wrapper) {
        if (Constant.SUCCESS_CODE.equals(wrapper.code)) {
            showMessage(wrapper.info);
        } else if (Constant.ERROR_CODE.equals(wrapper.code)) {

            if (mIsSms == SMS) {
                mSmsPhone = getText(mEdtLoginUsername);
                mPresenter.sendSms(mSmsPhone, AppCenter.getTokenKey(), "login", Constant.PLATFORM);
            } else {
                if (TextUtils.isEmpty(pwd)) {
                    showMessage("请输入密码");
                    return;
                }
                mPresenter.login(phone, pwd, AppCenter.getTokenKey(), Build.VERSION.RELEASE, mModel);
            }
        } else {
            showMessage(wrapper.info);
        }
    }

    @Override
    public void sendSuccess(HttpWrapper<String> wrapper) {
        if (Constant.SUCCESS_CODE.equals(wrapper.getCode())) {
            time();
            mSmsCode = wrapper.data;
        } else {
            showMessage(wrapper.getInfo());
        }
    }

    public void time() {
        showMessage("成功发送验证码");
        Logger.i("验证码倒计时开始");
        mLoginSend.setEnabled(false);
        addSubscription(U.countdownFlowable(59)            //倒计时60秒
                .subscribe(
                        time -> mLoginSend.setText(U.connectString("重新发送", "(", time, ")")),    //每秒赋值
                        U::errorUtil,             //提示错误信息
                        () -> {
                            mLoginSend.setEnabled(true);
                            mLoginSend.setText(getString(R.string.reSendyzm));
                        }));
    }

    @Override
    protected boolean needFullScreen() {
        return true;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

}
